# 导入模块
import json
import logging
import time
import datetime
import hashlib

import requests

from utils import *

logger = logging.getLogger('wx')

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) "
                  "Chrome/67.0.3396.87 Safari/537.36"
}

order_row_api = 'jd.union.open.order.row.query'
sku_info_api = 'jd.union.open.goods.promotiongoodsinfo.query'

# 查看地址：京东联盟后台->推广管理->导购媒体管理->查看
appkey = 'xxxxxx'
appsecret = 'xxxxxxx'


# 查询京东联盟的订单
def get_order():
    # timestamp = '2020-08-12 01:58:02'
    # last_min = get_last_min_ts()
    last_min = datetime.datetime.now() - datetime.timedelta(minutes=1)
    # last_x_min = get_last_x_min_ts(2)
    last_x_min = datetime.datetime.now() - datetime.timedelta(minutes=5)
    timestamp = last_min.strftime('%Y-%m-%d %H:%M:%S')
    start_time = last_x_min.strftime('%Y-%m-%d %H:%M:00')
    # start_time = '2020-09-15 06:04:02'
    end_time = last_min.strftime('%Y-%m-%d %H:%M:59')
    # end_time = '2020-09-15 06:10:02'

    str_to_sign = appsecret + 'app_key' + appkey + 'formatjsonmethod' + order_row_api + 'param_json{"orderReq":{"startTime":"' + start_time + '","endTime":"' + end_time + '","pageIndex":1,"pageSize":20,"type":3}}sign_methodmd5timestamp' + timestamp + 'v1.0' + appsecret

    hl = hashlib.md5()
    hl.update(str_to_sign.encode(encoding='utf-8'))
    sign = hl.hexdigest().upper()

    url = 'https://router.jd.com/api?v=1.0&method=' + order_row_api + '&access_token=&app_key=' + appkey + '&sign_method=md5&format=json&timestamp=' + timestamp + '&sign=' + sign + '&param_json={"orderReq":{"startTime":"' + start_time + '","endTime":"' + end_time + '","pageIndex":1,"pageSize":20,"type":3}}'

    try:
        response = requests.get(url, headers=headers)
    except BaseException as e:
        return None, e

    if response.text == '':
        logger.info(order_row_api + " response empty")
        return order_row_api + " response empty"

    try:
        json_data = json.loads(response.text)
    except json.decoder.JSONDecodeError as e:
        msg = 'json.loads(response.text) error. msg:{} response.text:{}'.format(e, response.text)
        return msg

    result = json_data.get('jd_union_open_order_row_query_response').get('result')
    data = json.loads(result)
    order_list = data.get('data')
    if order_list is None:
        return ''
    else:
        in_result = ''
        in_goods_num = 0
        in_fee_total = 0
        in_sku_desc = ''
        for order in order_list:
            today_date = datetime.datetime.now().strftime('%Y-%m-%d')
            if order.get('validCode') == 16 and order.get('orderTime').startswith(today_date):
                estimate_fee = order.get('estimateFee')  # 预计佣金
                if estimate_fee > 0:
                    sku_name = order.get('skuName')
                    estimate_cos_price = order.get('estimateCosPrice')  # 订单价格
                    commission_rate = order.get('commissionRate')  # 佣金比例
                    in_sku_desc += '\n\n' + sku_name + '\n订单价格：' + str(estimate_cos_price) + '\n佣金比例：' + str(commission_rate) + '\n预计佣金：' + str(estimate_fee)
                    in_goods_num += 1
                    in_fee_total += estimate_fee

        if in_goods_num > 0 and in_fee_total > 1:
            in_result += '恭喜, 新增佣金 ' + str(int(in_fee_total)) + ', 新增订单 ' + str(in_goods_num) + in_sku_desc

        if in_result != '':
            return in_result
        else:
            return ''


if __name__ == "__main__":
    print(get_order())
